package com.exchange.controller;

import com.exchange.dto.OrderDto;
import com.exchange.entity.Order;
import com.exchange.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
@PreAuthorize("hasRole('MERCHANT') or hasRole('ADMIN')")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @GetMapping
    public ResponseEntity<List<OrderDto>> getOrdersByMerchant() {
        // In a real implementation, we'd get the current merchant's ID from the security context
        // For now, using a placeholder
        Long currentMerchantId = 1L; // Placeholder - should come from security context
        List<OrderDto> orders = orderService.findByMerchantId(currentMerchantId);
        return ResponseEntity.ok(orders);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<OrderDto> getOrderById(@PathVariable Long id) {
        return orderService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public ResponseEntity<OrderDto> createOrder(@RequestBody Order order) {
        // In a real implementation, we'd get the current merchant's ID from the security context
        // For now, using a placeholder
        Long currentMerchantId = 1L; // Placeholder - should come from security context
        OrderDto createdOrder = orderService.createOrder(order, currentMerchantId);
        return ResponseEntity.ok(createdOrder);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<OrderDto> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        // This would typically be used for status updates
        return orderService.updateOrderStatus(id, order.getOrderStatus())
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
        boolean deleted = orderService.deleteOrder(id);
        return deleted ? ResponseEntity.ok().build() : ResponseEntity.notFound().build();
    }
    
    // API for customers to track their orders
    @GetMapping("/track/{orderNumber}")
    @PreAuthorize("permitAll")  // Allow any user to track an order with order number
    public ResponseEntity<OrderDto> trackOrder(@PathVariable String orderNumber) {
        return orderService.findByOrderNumber(orderNumber)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}